package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    //保存用户信息
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //上传用户头像
    public void updateHead(MultipartFile headPhoto, Long id) {
        try {
            //上传图片到阿里云oss，获取图像地址
            String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
            //调用百度云人脸识别aip，进行人脸识别
            boolean detect = aipFaceTemplate.detect(url);
            //若：包含人脸
            if (detect) {
                UserInfo userInfo = new UserInfo();
                userInfo.setAvatar(url);
                userInfo.setId(id);
                userInfoApi.update(userInfo);
            } else {
                throw new BusinessException(ErrorResult.faceError());
            }
        } catch (Exception e) {
            log.error("io异常");
        }
    }

    //根据id查询
    public UserInfoVo findById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);
        UserInfoVo userInfoVo = new UserInfoVo();
        //文件拷贝，只拷贝同名同类型的属性
        BeanUtils.copyProperties(userInfo, userInfoVo);
        //判断年龄非空
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    //更新用户信息
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}